package com.bit.springblogdemo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bit.springblogdemo.common.exception.BlogException;
import com.bit.springblogdemo.common.util.BeanTransUtils;
import com.bit.springblogdemo.common.util.JwtUtils;
import com.bit.springblogdemo.common.util.SecurityUtils;
import com.bit.springblogdemo.mapper.UserInfoMapper;
import com.bit.springblogdemo.pojo.dataobject.BlogInfo;
import com.bit.springblogdemo.pojo.dataobject.UserInfo;
import com.bit.springblogdemo.pojo.request.UserLoginRequset;
import com.bit.springblogdemo.pojo.response.UserInfoResponse;
import com.bit.springblogdemo.pojo.response.UserLoginResponse;
import com.bit.springblogdemo.service.BlogService;
import com.bit.springblogdemo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource(name="blogServiceImpl")
    BlogService blogService;
    @Override
    public UserLoginResponse checkpassword(UserLoginRequset userLoginRequset) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, userLoginRequset.getUserName())
                .eq(UserInfo::getDeleteFlag, 0);
        //查询数据库
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null) {
           throw new BlogException("用户不存在");
        }

        //判断密码是否正确
        /*if(!userLoginRequset.getPassword().equals(userInfo.getPassword())){
            throw new BlogException("用户密码错误");
        }*/
        if(!SecurityUtils.verify(userLoginRequset.getPassword(), userInfo.getPassword())){  //这里加上校验加密后的密码了
            throw new BlogException("用户密码错误");
        }
        //密码正确，返回token
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("name",userInfo.getUserName());
        String token = JwtUtils.genToken(map);
        return new UserLoginResponse(userInfo.getId(),token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0)
                .eq(UserInfo::getId, userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return BeanTransUtils.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        //1根据blogId来获取博客信息包含作责的Id
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if(blogInfo == null||blogInfo.getUserId()<=0){
           throw new BlogException("博客不存在");
        }
        //2.根据blogId 来获取博客信息
        return getUserInfo(blogInfo.getUserId());
    }


}
